package com.cc.controller;

import com.cc.annotation.MyDate;
import com.cc.entity.User;
import com.cc.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("user")
@Slf4j
public class UserController {
    @Resource
    private IUserService iUserService;
    //TODO 一、单个参数绑定
    @RequestMapping("/list")
    public String list(@RequestParam(value = "page", defaultValue = "1") int page,
                       Model model) {
        log.debug("进入UserController的list方法....... page："+page);
        //TODO 1. 获取参数，这里springmvc帮我们自动绑定了参数，相比servlet我们无需在通过
        //request.getParameter("page")来获取url参数值了
        //TODO 2.调用service层分页查询用户信息
        List<User> userList = iUserService.list(page);
        log.debug("分页查询用户列表信息，userList："+userList);
        //TODO 3.绑定参数到jsp页面
        model.addAttribute("userList",userList);
        return "user/list";
    }
    @RequestMapping("/to_add")
    public String toAdd(){
        return "user/add";
    }
    //TODO 二、引用类型参数  添加用户
    @RequestMapping("add")
    public void add(User user, HttpServletResponse response) throws IOException {// request.getParamerter("username");
        log.debug("user===>{}" , user);
        // 1.调用service，添加用户
        boolean result = iUserService.save(user);
        // 2.返回操作的状态："success"或"failed"
        if(result) {
            response.getWriter().write("success");
        }else {
            response.getWriter().write("failed");
        }

    }
    // TODO 三、自定义参数处理器，添加用户
    @RequestMapping("add2")
    public void add2(@MyDate(params = "birthday", pattern = "yyyy-MM-dd")
                            User user,HttpServletResponse response) throws IOException {// request.getParamerter("username");
        log.debug("user===>{}" ,user);
        // 1.调用service，添加用户
        boolean result = iUserService.save(user);
        // 2.返回操作的状态："success"或"failed"
        if(result) {
            response.getWriter().write("success");
        }else {
            response.getWriter().write("failed");
        }

    }

    @RequestMapping("/detail")
    public String detail(int id,Model model) {
        ModelAndView mav = new ModelAndView();
        // 1.调用service层查询用户详情
        User user = iUserService.detail(id);
        // 2.返回model 和view
        model.addAttribute("detail",user);
        return "user/edit";
    }
    //TODO 四、路径参数
    // http://localhost:8080/nd-springmvc01-base07/user/delete/47
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable("id") int id,
                         HttpServletRequest requst,
                         HttpServletResponse response,
                         @CookieValue("JSESSIONID") String value) {
        System.out.println("JSESSIONID==>" + value);
        // 1.调用service层根id删除用户
        boolean flag = iUserService.delete(id);
        if (flag) {
            // 获取session
            HttpSession session = requst.getSession();
            // 获取application
            ServletContext appContext = requst.getServletContext();
            session.setAttribute("opt_del_flag", "true");
            return "redirect:/user/list";// 重定向：不是在一次请求范围内,
        }
        return null;
    }

    @RequestMapping("/edit")
    public String edit(User user) throws Exception {
        // 1.调用service根据用户id进行更新
        boolean flag = iUserService.update(user);
        if (!flag) {
            throw new Exception("更新失败！！");
        }
        return "redirect:list";
    }

    //TODO 五、数组集合类型参数
    @RequestMapping("/batch_del")
    public String batchDelete(int[] ids) {
        log.debug("UserController  batchDelte...... ids="+ Arrays.toString(ids));
        boolean flag = iUserService.batchDelete(ids);
        return "redirect:list";
    }

    //TODO 六、默认值参数，见TestControlelr

    //TODO 七、返回值为ModelAndView
    @RequestMapping("/detail2")
    public ModelAndView detail(int id) {
        ModelAndView mav = new ModelAndView();
        // 1.调用service层查询用户详情
        User user = iUserService.detail(id);
        // 2.返回model 和view
        mav.addObject("detail", user);// request.setAttribute();
        mav.setViewName("user/edit");
        return mav;
    }

    //TODO 八、void返回值
    @RequestMapping("/detail3")
    public void  detail(int id,HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        ModelAndView mav = new ModelAndView();
        // 1.调用service层查询用户详情
        User user = iUserService.detail(id);
        // 2.返回数据 和view
        request.setAttribute("detail",user);
        request.getRequestDispatcher("/WEB-INF/jsp/user/edit.jsp").forward(request,response);
    }
}
